package com.briup.ch10;

/**
 * @author yuxi
 * @version 1.0
 * @date 2025/10/13
 * @Description:
 */

//线程同步：原本各执行各的（异步），现在统一了，上锁就是阻塞状态
//    操作相同的资源（共享内存），利用同步锁synchronized
//    1.锁代码块   2.锁方法
//    保证所有线程都是同一把锁，锁同一个对象
class TicketRun implements Runnable{
    private int num=100;//增，删，改，修改同一份数据
    //private final Object lock=new Object();
    @Override
    public void run() {
        while(num>0){
            //synchronized (lock){
            synchronized (this){
                num--;
                System.out.println(Thread.currentThread().getName()+"已卖出一张票，还剩余:"+num);
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
public class Test07 {
    public static void main(String[] args) {
        TicketRun t=new TicketRun();
        Thread t1=new Thread(t,"售票员A");
        Thread t2=new Thread(t,"售票员B");
        Thread t3=new Thread(t,"售票员C");
        t1.start();
        t2.start();
        t3.start();

    }
}
